<template>
	<view class="apply-for-wrapper" :style="{paddingTop: paddingTop + 'px'}">
		<navBar title="申请轮胎售后" marginLeft="30%"/>
		<view class="apply-for-content" :style="{top: paddingTop + 'px'}">
			<view class="form-card">
				<view class="form-title">基本信息</view>
				<view class="form-box">
					<u--form labelPosition="left" :model="baseInfo" :rules="baseRules" ref="baseInfo" labelWidth="150"
						labelAlign="right">
						<view class="form-item-custom">
							<view class="label require">申请人姓名</view>
							<u-form-item prop="userName" borderBottom>
								<u--input v-model="baseInfo.userName" border="none"></u--input>
							</u-form-item>
						</view>
						<view class="form-item-custom">
							<view class="label require">申请人电话</view>
							<u-form-item prop="phone" borderBottom>
								<u--input v-model="baseInfo.phone" border="none"></u--input>
							</u-form-item>
						</view>
						<view class="form-item-custom">
							<view class="label require">所在地区</view>
							<picker @change="chooseregion" mode="region" style="width: calc(100% - 190rpx);"
								:value="[baseInfo.province,baseInfo.city,baseInfo.county]">
								<view class="address">
									<u-form-item prop="addressInfo" borderBottom>
										<u--textarea v-model="baseInfo.addressInfo" border="none" :readonly="true"
											:autoHeight="true">
										</u--textarea>
									</u-form-item>
								</view>
							</picker>
							<view class="arrow-icon">
								<u-icon name="arrow-right" size="35" color="#000"></u-icon>
							</view>
						</view>
						<view class="form-item-custom">
							<view class="label require">详细地址</view>
							<u-form-item prop="address" borderBottom>
								<u--textarea v-model="baseInfo.address" border="none" placeholder="请填写详细地址"
									:autoHeight="true">
								</u--textarea>
							</u-form-item>
						</view>
						<view class="form-item-custom" @click="checkedStore">
							<view class="label require">售后门店</view>
							<u-form-item prop="storeName" borderBottom>
								<u--input v-model="baseInfo.storeName" border="none" readonly></u--input>
							</u-form-item>
							<view class="arrow-icon">
								<u-icon name="arrow-right" size="35" color="#000"></u-icon>
							</view>
						</view>
						<view class="form-item-custom" @click="openTire">
							<view class="label require">胎码</view>
							<u-form-item prop="itemNumber" borderBottom>
								<u--input v-model="baseInfo.itemNumber" border="none" :readonly="tireCode[0].length>0"
									:placeholder="tireCode[0].length>0?'请选择胎码':'请输入胎码'"></u--input>
							</u-form-item>
							<view class="arrow-icon" v-if="tireCode[0].length>0">
								<u-icon name="arrow-right" size="35" color="#000"></u-icon>
							</view>
						</view>
					</u--form>
				</view>
				<view class="form-title">备注</view>
				<view class="text-area">
					<text class="zs">{{baseInfo.remarks.length}}/100</text>
					<u--textarea v-model="baseInfo.remarks" placeholder="请填写申请轮胎质保的具体原因" height="140" maxlength="100">
					</u--textarea>
				</view>
			</view>
			<view class="form-card">
				<view class="form-title">购买信息</view>
				<view class="form-box">
					<u--form labelPosition="left" :model="applyInfo" :rules="payRules" ref="payInfo" labelWidth="150"
						labelAlign="right">
						<view class="form-item-custom">
							<view class="label">购买地区</view>
							<u-form-item prop="userName" borderBottom>
								<u--input v-model="applyInfo.purchaseArea" border="none" :readonly="true"></u--input>
							</u-form-item>
						</view>
						<view class="form-item-custom">
							<view class="label">购买门店</view>
							<u-form-item prop="userName" borderBottom>
								<u--input v-model="applyInfo.terminalName" border="none" :readonly="true"></u--input>
							</u-form-item>
						</view>
						<view class="form-item-custom">
							<view class="label">购买日期</view>
							<u-form-item prop="userName" borderBottom>
								<u--input v-model="applyInfo.orderCreateDate" border="none" :readonly="true"></u--input>
							</u-form-item>
						</view>
					</u--form>
				</view>
			</view>
			<view class="form-card">
				<view class="form-title">轮胎照片（ 每个最多1张 ）</view>
				<view class="upload-list" v-for="(item,index) in claimFiles">
					<view class="upload-title">
						<view class="title" :class="{'active':item.required}">{{ item.name }}</view>
						<view class="tip" @click="onPreview(item.sampleFile)">照片示例</view>
					</view>
					<view class="upload-box">
						<u-upload accept="image" :fileList="item.fileList"  multiple :previewFullImage="true"
							@afterRead="event=>afterRead(event,index)" @delete="deletePic(index)" :maxCount="1"
							width="110" height="88">
							<image
								:src="item.fileList.length == 0?'https://coach-vehicle-uat-1313990257.cos.ap-beijing.myqcloud.com/miniapp/guarantee/upload1.png':item.fileList.url"
								mode="widthFix" style="width: 110px;height: 88px;"></image>
						</u-upload>
					</view>
				</view>
			</view>
			<view class="tip-content">
				<view class="content">
					<text class="dot"></text>
					申请通过后可享受轮胎售后，若申请长时间未通过，请致电
					<text class="phone" @click="callPhone">400-696-5399</text>
					电话提醒审核员尽快审核。
				</view>
			</view>
		</view>
		<view class="footer">
			<u-button type="primary" text="提交申请" @click="onSave()"></u-button>
		</view>
		<u-picker :show="tireShow" :columns="tireCode" @cancel="cancelPicker" @confirm="onConfirmTire"></u-picker>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '@/common/config'
	import navBar from '@/components/navBar.vue'
	import QQMapWX from '@/lib/qqmap-wx-jssdk.js'
	import {
		mapGetters
	} from 'vuex'

	export default {
		components: {
			navBar
		},
		data() {
			return {
				detailInfo: {},
				paddingTop: '',
				baseInfo: {
					userName: '',
					phone: '',
					province: '',
					remarks: '',
					goodsId: '',
					insuranceId: '',
					itemNumber: '',
					address: '',
					addressInfo: '',
					storeName:'',
					serviceStoreId:'',
					claimId:''
				},
				addressInfo: '',
				baseRules: {
					phone: [{
							required: true,
							message: '手机号码不能为空！',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确！',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],

					userName: [{
							required: true,
							message: '姓名不能为空！',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								var isright = /^[\u4e00-\u9fa5]{2,8}$/.test(value)
								return isright
							},
							message: '姓名只能输入中文！',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}

					],
					addressInfo: [{
						required: true,
						message: '所在地区不能为空！',
						trigger: ['change', 'blur'],
					}],
					address: [{
						required: true,
						message: '详细地址不能为空！',
						trigger: ['change', 'blur'],
					}],
					storeName:[{
						required: true,
						message: '售后门店不能为空！',
						trigger: ['change', 'blur'],
					}],
					itemNumber: [{
							required: true,
							message: '胎码不能为空！',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								var isright = /[\u4E00-\u9FA5]/g.test(value)
								return !isright
							},
							message: '胎码只允许英文数字和符号！',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}
					],

				},
				applyInfo: {

				},
				payRules: [],
				fileList: [],
				claimFiles: [{
					fileUrl: '',
					name: '',
					positionCode: ''
				}],
				tireShow: false,
				tireCode: []

			}
		},
		computed: {
			...mapGetters('user', ['getUserInfo']),
		},
		methods: {
			//选择省市区
			chooseregion: function(e) {
				let code = e.detail.code
				let val = e.detail.value
				if (code && code.length === 3) {
					this.baseInfo.province = val[0]
					this.baseInfo.city = val[1]
					this.baseInfo.county = val[2]
				}
				if (val) {
					this.baseInfo.addressInfo = val.join('')
					// this.address =  val.join('')
					// this.$refs.formRef.validate()
				}
			},
			// 调用腾讯SDK获取当前定位城市信息
			reverseAddress() {
				const qqmapsdk = new QQMapWX({
					// 测试key
					key: this.$mapKey
				})
				qqmapsdk.reverseGeocoder({
					success: async (res) => {
						let result = res.result.address_component
						this.baseInfo.province = result.province
						this.baseInfo.city = result.city
						this.baseInfo.county = result.district
						this.baseInfo.addressInfo = result.province + result.city + result.district
						this.baseInfo.address = res.result.address
					},
					fail: (error) => {
						console.error('error', error);
					},
				})
			},
			//初始化表单
			async initForm(val) {
				const data = this.applyInfo = val.data
				const index = val.index
				this.tireCode = []
				const {
					userName,
					phone,
					province,
					city,
					id,
					insuranceId,
					itemNumber,
					serviceStore,
					claimFiles,
					country,
					claimItem,
					serviceTerminalInfo,
					remarks
				} = data
				this.baseInfo.userName = userName
				this.baseInfo.phone = phone
				this.baseInfo.province = province
				this.baseInfo.city = city
				this.baseInfo.country = country
				this.baseInfo.goodsId = data.goodsList[index].goodsId
				this.baseInfo.insuranceId = insuranceId ? insuranceId:id
				this.baseInfo.itemNumber = itemNumber?itemNumber:''
				this.baseInfo.addressInfo = province + city + country
			    this.baseInfo.storeName = serviceStore?serviceStore:data.terminalName
				this.baseInfo.serviceStoreId = serviceTerminalInfo ? serviceTerminalInfo.id:data.terminalId
				this.baseInfo.remarks = remarks&&insuranceId?remarks:''
				this.baseInfo.claimId = claimItem?claimItem.claimId:''
				data.goodsList[index].insuranceItems.forEach(item => {
					if (item.itemNumber&&!item.claimId) {
						item.text = item.itemNumber
						this.tireCode.push(item)
					}
				})
				this.tireCode = [this.tireCode]
				try {
					const res = await this.$request({
						method: 'get',
						url: `/ltb-center/union-insurance-claim/claimPositionConfig`,
						data: {
							userId: this.getUserInfo.id
						}
					})
					res.datas.forEach(item => {
						item.fileList = []
					})
					if(claimFiles&&claimFiles.length){
						claimFiles.forEach(item => {
							item.url = item.fileUrl
							res.datas.forEach(list => {
								if(item.positionCode == list.positionCode){
									list.fileList = [item]
								}
							})
						})
					}
					this.claimFiles = res.datas
					uni.hideLoading()
				} catch (res) {
					uni.hideLoading()
					uni.showToast({
						title: '请求失败',
						icon: 'error'
					})
				}
				this.reverseAddress()

				uni.stopPullDownRefresh();
			},
			//选择门店
			checkedStore() {
        let url = ''
        if(this.baseInfo.serviceStoreId) {
          url = `/components/selectStore?type=guarantee&serviceStoreId=${this.baseInfo.serviceStoreId}` //若有门店信息则在选择页面回显
        } else {
          url: '/components/selectStore?type=guarantee'
        }
				uni.navigateTo({
					url: url,
					events: {
						//获取下级页面传递回来的参数
						setStoreAdress: data => {
							this.baseInfo.storeName = data.name
							this.baseInfo.serviceStoreId = data.id
						}
					}
				})
			},
			//显示胎码列表
			openTire() {
				if (this.tireCode[0].length == 0) {
					return false;
				}
				this.tireShow = true
			},
			//确认胎码
			onConfirmTire(val) {
				this.baseInfo.itemNumber = val.value[0].itemNumber
				this.tireShow = false
			},
			//取消胎码
			cancelPicker(){
				this.tireShow = false
			},
			//图片上传
			async afterRead(event, index) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				const item = event.file[0];
				this.claimFiles[index]['fileList'].push({
					...item,
					//提示上传中
					status: 'uploading',
					message: '上传中'
				});
				// 获取本地读取文件路径
				const url = item.url;
				//result为上传成功的响应数据
				let result = await this.uploadFilePromise(url);
				//上传成功提示，以及回显
				this.claimFiles[index]['fileList'] = []
				this.claimFiles[index]['fileList'].push({
					status: 'success',
					message: '上传成功',
					// 二进制文件流用于预览图片
					url: result
				});
			},
			uploadFilePromise(url, index) {
				// 请求头
				var header = {
					'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
					"Content-Type": "multipart/form-data",
				};
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						// 完整上传路径 H5端需要解决跨域问题
						url: `${baseUrl}/user-center/app-file/upload-file`,
						// 本地上传读取到的url
						filePath: url,
						name: 'file',
						// 请求头
						header: header,
						// 附加表单对象
						formData: {
							user: 'test'
						},
						success: res => {
							const result = JSON.parse(res.data);
							const formUrl = result.datas;
							resolve(formUrl)
						}
					});
				});
			},
			//删除图片
			deletePic(index) {
				this.claimFiles[index]['fileList'] = []
			},
			//复制
			onCopy(data) {
				uni.setClipboardData({
					data: data, // 复制的内容 
					success: function() {
						uni.showToast({
							title: '复制成功',
							duration: 1000
						})
					}
				});
			},
			//图片预览
			onPreview(url) {
				var urlList = []
				urlList.push(url)
				uni.previewImage({
					indicator: "number",
					loop: true,
					urls: urlList
				})
			},
			//电话
			callPhone() {
				// 区分设备
				if (uni.getSystemInfoSync().osName === 'ios') {
					uni.makePhoneCall({
						phoneNumber: '400-696-5399'
					})
				} else {
					uni.showModal({
						title: "拨打电话",
						content: '400-696-5399',
						confirmText: "确认",
						cancelText: "取消",
						success: res => {
							if (res.confirm) {
								uni.makePhoneCall({
									phoneNumber: '400-696-5399'
								})
							}
						}
					})
				}
			},
			//提交表单
			async onSave() {
				//检测必填项是否为空		
				if (!this.baseInfo.userName || !this.baseInfo.addressInfo || !this.baseInfo.itemNumber || !this
					.baseInfo.phone || !this.baseInfo.address||!this.baseInfo.storeName) {
					uni.showToast({
						title: '必填项不能为空！',
						icon: 'error'
					})
					return false
				}
				if (!/^[\u4e00-\u9fa5]{2,8}$/.test(this.baseInfo.userName)) {
					uni.showToast({
						title: '姓名输入有误！',
						icon: 'error'
					})
					return false
				}
				if (/[\u4E00-\u9FA5]/g.test(this.baseInfo.itemNumber)) {
					uni.showToast({
						title: '胎码输入有误！',
						icon: 'error'
					})
					return false
				}

				//检测图片是否上传
				let flag = false
				this.claimFiles.forEach(item => {
					if (item.fileList.length == 0 && item.required) {
						flag = true
						return;
					}
				})
				if (flag) {
					uni.showToast({
						title: '照片不能为空！',
						icon: 'error'
					})
					return false
				}

				let claimFilesObj = []
				let params = JSON.parse(JSON.stringify(this.baseInfo))
				uni.showLoading({
					title: '正在提交...'
				})
				this.claimFiles.forEach(item => {
					if (item.fileList.length > 0) {
						let obj = {
							fileUrl: item.fileList.length > 0 ? item.fileList[0].url : '',
							name: item.name,
							positionCode: item.positionCode

						}
						claimFilesObj.push(obj)
					}

				})
				params.claimFiles = claimFilesObj
				try {
					const res = await this.$request({
						method: 'post',
						url: `/ltb-center/union-insurance-claim/apply`,
						data: params
					})
					uni.navigateTo({
						url: `/indexPack/guarantee/applySuccess?id=${res.datas}&resubmit=${this.applyInfo.serviceTerminalInfo?0:this.applyInfo.id}`
					});
					uni.hideLoading()
				} catch (res) {
					uni.hideLoading()
					this.$refs.uToast.show({
						message: res.respMsg || '请求失败',
						position: 'top',
						duration: 2000
					})
				}

			}

		},
		onLoad(option) {
			this.paddingTop = this.$store.getters['global/getSystemInfo'].navBarHeight
			uni.showLoading({
				title: '加载中...'
			})
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('formInfo', this.initForm)
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.baseInfo.setRules(this.baseRules)
		},

	}
</script>

<style lang="scss" scoped>
	.apply-for-wrapper {
		position: relative;
		padding-bottom: env(safe-area-inset-bottom);

		.apply-for-content {
			padding-bottom: 130rpx;

			.form-card {
				padding: 36rpx 32rpx;
				margin-top: 20rpx;
				background: #fff;

				.form-title {
					font-size: 14px;
					font-weight: 500;
					color: rgba(0, 0, 0, 0.85);
					padding-bottom: 36rpx;
				}

				.form-box {
					padding-bottom: 24rpx;

					.form-item-custom {
						display: flex;
						align-items: center;
						position: relative;

						.label {
							width: 190rpx;
							text-align: left;
							font-size: 14px;
							padding-left: 20rpx;
							color: rgba(0, 0, 0, 0.65);
						}

						.require {
							position: relative;
						}

						.require::after {
							position: absolute;
							top: 15%;
							left: 0;
							content: '*';
							color: red;
						}

						/deep/ .u-textarea {
							padding: 0 !important;
							width: calc(100% - 50rpx) !important;

						}

						/deep/ .u-form-item {
							width: calc(100% - 210rpx);

							.u-form-item__body__right__message {
								margin: 0 !important;
							}
						}

						.address {
							/deep/ .u-form-item {
								width: 100%;
							}
						}

						.arrow-icon {
							position: absolute;
							width: 40rpx;
							height: 40rpx;
							right: 0;
							bottom: 22rpx;
						}
					}
				}

				.text-area {
					padding-bottom: 24rpx;
					position: relative;

					.zs {
						position: absolute;
						top: -60rpx;
						font-size: 14px;
						right: 0;
					}

					/deep/ .u-textarea {

						width: auto;

					}
				}

				.upload-list {
					padding-bottom: 32rpx;
					padding-left: 20rpx;

					/deep/ .u-upload__wrap__preview__image {
						width: 204rpx !important;
						height: 162rpx !important;
					}

					.upload-title {
						display: flex;
						justify-content: space-between;
						font-size: 14px;
						padding-bottom: 30rpx;

						.title {
							position: relative;
							color: rgba(0, 0, 0, 0.65);
						}

						.active::after {
							position: absolute;
							top: 15%;
							left: -20rpx;
							content: '*';
							color: red;
						}

						.tip {
							color: #CF1A1B;
						}
					}
				}
			}

			.tip-content {
				padding: 32rpx;

				.content {
					width: calc(100% - 48rpx);
					padding: 40rpx 24rpx;
					background: rgb(255, 222, 222);
					color: rgba(0, 0, 0, 0.65);
					font-size: 13px;

					.dot {
						display: inline-block;
						background: #CF1A1B;
						width: 10rpx;
						height: 10rpx;
						margin-right: 10rpx;
						border-radius: 50%;
						vertical-align: middle;
					}

					.phone {
						color: #CF1A1B;
					}
				}
			}
		}

		.footer {
			background: #fff;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 30rpx 32rpx;
			z-index: 3;
		}
	}
</style>
